<template>
  <div class="room-status-container">
    <el-card>
      <template #header>
        <div class="page-header">
          <h3>会议室状态管理</h3>
          <el-button type="primary" @click="fetchRoomList">刷新</el-button>
          <el-radio-group v-model="viewType" size="small">
            <el-radio-button label="grid">网格视图</el-radio-button>
            <el-radio-button label="list">列表视图</el-radio-button>
          </el-radio-group>
        </div>
      </template>

      <!-- 网格视图 -->
      <div v-if="viewType === 'grid'" class="room-grid">
        <el-card 
          v-for="room in roomList" 
          :key="room.id" 
          class="room-card"
          :class="`room-card-${room.status}`"
        >
          <template #header>
            <div class="room-card-header">
              <span>{{ room.name }}</span>
              <el-tag :type="getStatusType(room.status)" size="small">
                {{ getStatusText(room.status) }}
              </el-tag>
            </div>
          </template>
          <div class="room-card-content">
            <p>类型：{{ room.type === 'classroom' ? '教室型' : '圆桌型' }}</p>
            <p>座位数：{{ room.capacity }}</p>
            <p>每小时价格：¥{{ room.price }}</p>
            <p>可用时间：{{ formatTime(room.availableTime.start) }} - {{ formatTime(room.availableTime.end) }}</p>
            <div class="room-card-actions">
              <el-button-group>
                <template v-if="room.status === 'idle'">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="handleStartUse(room)"
                  >
                    开始使用
                  </el-button>
                  <el-button 
                    type="warning" 
                    size="small"
                    @click="handleSetMaintenance(room)"
                  >
                    设为维护
                  </el-button>
                </template>

                <template v-if="room.status === 'reserved'">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="handleStartUse(room)"
                  >
                    开始使用
                  </el-button>
                </template>

                <template v-if="room.status === 'in_use'">
                  <el-button 
                    type="success" 
                    size="small"
                    @click="setIdle(room)"
                  >
                    结束使用
                  </el-button>
                  <el-button 
                    type="warning" 
                    size="small"
                    @click="handleSetMaintenance(room)"
                  >
                    设为维护
                  </el-button>
                </template>

                <template v-if="room.status === 'maintenance'">
                  <el-button 
                    type="info" 
                    size="small"
                    @click="setIdle(room)"
                  >
                    维护完成
                  </el-button>
                </template>
              </el-button-group>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 列表视图 -->
      <div v-else>
        <el-table :data="roomList" style="width: 100%">
          <el-table-column prop="name" label="会议室名称" />
          <el-table-column prop="type" label="类型">
            <template #default="{ row }">
              {{ row.type === 'classroom' ? '教室型' : '圆桌型' }}
            </template>
          </el-table-column>
          <el-table-column prop="capacity" label="座位数" />
          <el-table-column prop="price" label="每小时价格" />
          <el-table-column label="可用时间">
            <template #default="{ row }">
              {{ formatTime(row.availableTime.start) }} - {{ formatTime(row.availableTime.end) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template #default="{ row }">
              <el-button-group>
                <template v-if="row.status === 'idle'">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="handleStartUse(row)"
                  >
                    开始使用
                  </el-button>
                  <el-button 
                    type="warning" 
                    size="small"
                    @click="handleSetMaintenance(row)"
                  >
                    设为维护
                  </el-button>
                </template>

                <template v-if="row.status === 'reserved'">
                  <el-button 
                    type="primary" 
                    size="small"
                    @click="handleStartUse(row)"
                  >
                    开始使用
                  </el-button>
                </template>

                <template v-if="row.status === 'in_use'">
                  <el-button 
                    type="success" 
                    size="small"
                    @click="setIdle(row)"
                  >
                    结束使用
                  </el-button>
                  <el-button 
                    type="warning" 
                    size="small"
                    @click="handleSetMaintenance(row)"
                  >
                    设为维护
                  </el-button>
                </template>

                <template v-if="row.status === 'maintenance'">
                  <el-button 
                    type="info" 
                    size="small"
                    @click="setIdle(row)"
                  >
                    维护完成
                  </el-button>
                </template>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 确认对话框 -->
    <el-dialog
      v-model="confirmDialogVisible"
      :title="confirmDialogTitle"
      width="400px"
    >
      <p v-if="selectedRoom">{{ confirmDialogMessage }}</p>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="confirmDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm" :loading="confirming">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>


  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRoomList, updateRoomStatus } from '../../api/meetingRoomApi'

const viewType = ref('grid')
const confirmDialogVisible = ref(false)
const selectedRoom = ref(null)
const confirming = ref(false)

const confirmDialogTitle = computed(() => {
  if (!selectedRoom.value) return ''
  const actionMap = {
    startUse: '开始使用会议室',
    endUse: '结束使用会议室',
    endMaintenance: '结束维护状态'
  }
  return actionMap[confirmAction.value] || ''
})

const confirmDialogMessage = computed(() => {
  if (!selectedRoom.value) return ''
  const messageMap = {
    startUse: `确认将会议室 "${selectedRoom.value.name}" 设置为使用中状态？`,
    endUse: `确认结束会议室 "${selectedRoom.value.name}" 的使用？`,
    endMaintenance: `确认会议室 "${selectedRoom.value.name}" 维护完成？`
  }
  return messageMap[confirmAction.value] || ''
})

const confirmAction = ref('')
const maintenanceForm = ref({
  reason: '',
  estimatedHours: 1
})

const roomList = ref([])
const loading = ref(false)

const fetchRoomList = async () => {
  loading.value = true
  try {
    const response = await getRoomList()
    console.log(response);
    
    if (response.flag) {
      roomList.value = response.result.map(room => ({
        id: room.roomId,
        name: room.name,
        type: room.type,
        capacity: room.maxCapacity,
        status: room.status,  // 使用字符串状态
        price: room.hourlyRentalPrice,
        availableTime: {
          start: room.availableStartTime,
          end: room.availableEndTime
        }
      }))
    } else {
      ElMessage.error(response.reason || '获取会议室列表失败')
    }
  } catch (error) {
    ElMessage.error('网络错误：' + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchRoomList()
})

const getStatusType = (status) => {
  const map = {
    idle: 'success',       // 空闲
    reserved: 'warning',     // 已预订
    in_use: 'primary',      // 使用中
    maintenance: 'danger',   // 维护中
    locked: 'info'       // 锁定中
  }
  return map[status] || 'info'
}

const getStatusText = (status) => {
  const map = {
    idle: '空闲',
    reserved: '预订',
    in_use: '使用',
    maintenance: '维护',
    locked: '锁定',
  }
  return map[status] || status
}

const handleStartUse = async (room) => {
  const params = {
    roomId: room.id,
    status: 'in_use'
  }
  console.log(params);
  
  try {
    const response = await updateRoomStatus(params)
    if (response.flag) {
      room.status = 'using'
      ElMessage.success('会议室开始使用成功')
      await fetchRoomList() // 刷新列表
    } else {
      ElMessage.error(response.reason || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

const setIdle = async (room) => {
  try {
    const response = await updateRoomStatus({
      roomId: room.id,
      status: 'idle'
    })
    if (response.flag) {
      room.status = 'idle'
      ElMessage.success('成功设置为空闲状态')
      await fetchRoomList() // 刷新列表
    } else {
      ElMessage.error(response.reason || '操作失败')
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}

const handleSetMaintenance = async (room) => {
  selectedRoom.value = room

  try {
    const response = await updateRoomStatus({
      roomId: selectedRoom.value.id,
      status: 'maintenance',
    })
    
    if (response.flag) {
      selectedRoom.value.status = 'maintenance'
      ElMessage.success('设置维护状态成功')
      await fetchRoomList() // 刷新列表
    } else {
      ElMessage.error(response.reason || '设置维护状态失败')
    }
  } catch (error) {
    ElMessage.error('操作失败: ' + error.message)
  }
}



const handleConfirm = () => {
  if (!selectedRoom.value || !confirmAction.value) return
  
  confirming.value = true
  // TODO: 调用相应的接口
  console.log('操作：', confirmAction.value, '会议室：', selectedRoom.value)
  
  setTimeout(() => {
    confirming.value = false
    confirmDialogVisible.value = false
    
    // 模拟更新状态
    const room = roomList.value.find(r => r.id === selectedRoom.value.id)
    if (room) {
      switch (confirmAction.value) {
        case 'startUse':
          room.status = 'using'
          break
        case 'endUse':
          room.status = 'idle'
          break
        case 'endMaintenance':
          room.status = 'idle'
          break
      }
    }
    
    ElMessage.success('操作成功')
  }, 1000)
}

const formatTime = (timeStr) => {
  if (!timeStr) return ''
  try {
    return new Date(timeStr).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
  } catch {
    return timeStr.split('T')[1].substring(0, 5) // 简单处理格式如 "1970-01-01T08:00:00.000+08:00"
  }
}
</script>

<style scoped>
.room-status-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.room-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.room-card {
  margin-bottom: 20px;
}

.room-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.room-card-content {
  padding: 10px 0;
}

.room-card-content p {
  margin: 5px 0;
  font-size: 14px;
}

.room-card-actions {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

.room-card-idle {
  border-left: 4px solid #67c23a;
}

.room-card-booked {
  border-left: 4px solid #e6a23c;
}

.room-card-using {
  border-left: 4px solid #409eff;
}

.room-card-maintenance {
  border-left: 4px solid #909399;
}

.room-card-closed {
  border-left: 4px solid #f56c6c;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 